<template>
  <el-dialog
    destroy-on-close
    title="添加"
    :visible.sync="isOpen"
    width="50%"
    append-to-body
    :close-on-click-modal="false"
    @close="cancel"
    id="addFingerDialog"
  >
    <div class="dialog">
      <el-form label-position="right" :model="form" ref="formRef" label-width="80px">
        <div v-for="fItem in fingerList" :key="fItem.identitySubType">
          <div class="type">
            {{ getFingerType(fItem.identitySubType) }}
          </div>
          <el-upload
            class="avatar-uploader"
            action="#"
            accept=".bmp"
            :count='1'
            :auto-upload="false"
            :on-change="(file, fileList) => getFile(file, fileList, fItem)"
            ref="uploadImg"
            :show-file-list="false"
          >
            <img v-if="fItem.url" :src="fItem.url" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            <div class="status" :class="getClassNameByFingerStatus(fItem.fingerStatus)">
              {{ fingerStatusMap[fItem.fingerStatus] }}
            </div>
          </el-upload>
        </div>
      </el-form>
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="submitForm(formRef)" :loading="btnLoading"
        >确 定
        </el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script>
import {
  fileUploadApi,
  delUploadPicApi
} from "@/api/community/person";

export default {
  name: 'addFinger',
  props: {
    personId: {
      type: String,
      default: '',
    },
    personName: {
      type: String,
      default: '',
    },
    personGender: {
      type: Number,
      default: 1,
    },
    fingerDataList: {
      type: Array,
      default: new Array(10)
    },
    fingerStatusMap: {
      type: Object,
      default: {
        '0': '无指纹',
        '1': '已生成',
        '2': '未生成',
        '-1': '生成失败',
        '99': '指纹已经存在'
      }
    }
  },
  data() {
    return {
      btnLoading: false,
      staticUserInfo: {
        personId: this.personId,
        personIDType: 0,
        personName: this.personName,
        personGender: Number(this.personGender),
        personType: 1,
        identityType: 7,
        // identitySubType: 1
        // identityData: '',
        // fingerUserId: -1
      },
      form: {
        data: [
          // {
          //   personId: this.personId,
          //   personIDType: 0,
          //   personName: this.personName,
          //   personGender: this.personGender,
          //   personType: 1,
          //   identityType: 7,
          //   identitySubType: 1,
          //   identityData: '',
          //   fingerUserId: -1
          // }
        ]
      },
      fingerList: [],
      isOpen: false,
      formRef: '',
      defaultEmptyFingerUserId: -1,
      defaultIdentityType: 7,
      fingerStatusClassMap: {
        '0': 'no-finger',
        '1': 'generated',
        '2': 'not-gen',
        '-1': 'gen-failed',
        '99': 'exist'
      },
      fingerTypeArr: ['左手大拇指', '左手食指', '左手中指', '左手无名指', '左手小拇指', '右手大拇指', '右手食指', '右手中指', '右手无名指', '右手小拇指']
    }
  },
  methods: {
    open() {
      this.isOpen = true
      this.btnLoading = false

      this.initUserFingers()
    },
    initUserFingers() {
      // 1. 用fingerDataList来生成初始form
      this.form = {
        // .map(v => v.identityType = this.defaultIdentityType) 修正后端identityType可能返回错误的问题 后续移除
        data: JSON.parse(JSON.stringify(this.fingerDataList))
      }
      // 2. 将form中的信息部分映射至fingerList以便组件遍历渲染
      this.fingerList = this.form.data.filter(d => d.fingerUserId !== -1).map(d => {
        return {
          identitySubType: d.identitySubType,
          url: d.url,
          fingerUserId: d.fingerUserId,
          fingerStatus: d.fingerStatus
        }
      })

      // 3. fingerList不足10条的部分用默认值填满.
      while (this.fingerList.length < 10) {
        let identitySubType = 0
        do {
          identitySubType++
        } while (this.fingerList.find(finger => finger.identitySubType === identitySubType))

        this.fingerList.push({
          identitySubType,
          url: '',
          fingerUserId: this.defaultEmptyFingerUserId,
          fingerStatus: '0'
        })
      }

      // 4. 将fingerList按identitySubType从小到大排序
      this.fingerList.sort((prev, next) => prev.identitySubType - next.identitySubType)

      // 5. 移除form中的多余字段url和fingerStatus
      this.form.data.forEach(d => {
        delete d.url
        delete d.fingerStatus
      })
    },
    cancel() {
      this.isOpen = false
    },
    submitForm() {
      this.$refs.formRef.validate((validate, fields) => {
        if (validate) {
          this.$emit("submitAddFinger", this.form)
        } else {
          console.log("error submit!", fields)
        }
      });
    },
    getFile(file, _, item) {
      const params = new FormData();
      params.append("fileType", 0);
      params.append("fileData", file.raw)

      if (file.size / 1024 / 1024 > 1) {
        this.$message.error("最大不超过1m!")
        return false;
      }

      fileUploadApi(params).then(res => {
        if (res) {
          item.url = URL.createObjectURL(file.raw)
          // console.log('33333333333', item)
          // 如果item.fingerUserId是-1，则说明是新增的，需要修改form(往form中push，但是total不超过10)
          // 否则，说明是修改的，需要form中对应的fingerUserId的一致的对象内容
          if (item.fingerUserId === -1) {
            const fingerInfo = this.form.data.find(d => d.identitySubType === item.identitySubType)
            if (fingerInfo) {
              fingerInfo.identityData = res.path
            } else {
              this.form.data.push({
                ...this.staticUserInfo,
                identityData: res.path,
                fingerUserId: item.fingerUserId,
                identitySubType: item.identitySubType
              })
            }
          } else {
            const fingerInfo = this.form.data.find(d => d.fingerUserId === item.fingerUserId)
            if (fingerInfo) {
              fingerInfo.identityData = res.path
            }
          }
          this.$message.success("上传成功")
        }
      })
    },
    getClassNameByFingerStatus(status) {
      return this.fingerStatusClassMap[status]
    },
    getFingerType(identitySubType) {
      return this.fingerTypeArr[identitySubType - 1]
    }
  },
}


</script>

<style lang="scss">
.el-dialog {
  max-width: 1080px;

  .dialog {
    padding: 10px;

    .el-form {
      display: flex;
      flex-flow: wrap row;

      .type {
        padding-left: 18px;
        margin-bottom: 6px;
      }

      .avatar-uploader {
        margin-right: 20px;
        margin-bottom: 20px;

        .el-upload {
          width: 152px;
          height: 152px;
          border: 1px dashed #d9d9d9;
          border-radius: 6px;
          cursor: pointer;
          position: relative;
          overflow: hidden;

          &:hover {
            border-color: #409eff;
          }

          .status {
            position: absolute;
            left: 20px;
            top: 8px;
            display: flex;
            align-items: center;
            color: #333333;

            &::before {
              content: '';
              display: block;
              width: 6px;
              height: 6px;
              border-radius: 50%;
              margin-right: 6px;
            }


            &.no-finger {
              &::before {
                background-color: #909399;
              }
            }

            &.generated {
              &::before {
                background-color: #67C23A;
              }
            }

            &.not-gen {
              &::before {
                background-color: #F56C6C;
              }
            }

            &.gen-failed {
              &::before {
                background-color: #F56C6C;
              }
            }

            &.exist {
              &::before {
                background-color: #E6A23C;
              }
            }
          }

          .avatar-uploader-icon {
            font-size: 28px;
            color: #8c939d;
            width: 152px;
            height: 152px;
            line-height: 152px;
            text-align: center;
          }

          .avatar {
            width: 92px;
            height: 92px;
            position: absolute;
            left: 50%;
            top: 52%;
            transform: translate(-50%, -50%);
          }
        }
      }
    }
  }
}
</style>
